package com.mcc.system.service.impl;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mcc.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mcc.common.annotation.DataSource;
import com.mcc.common.constant.Constants;
import com.mcc.common.constant.UserConstants;
import com.mcc.common.core.redis.RedisCache;
import com.mcc.common.core.text.Convert;
import com.mcc.common.enums.DataSourceType;
import com.mcc.common.exception.CustomException;
import com.mcc.common.utils.StringUtils;
import com.mcc.system.domain.SysConfig;
import com.mcc.system.mapper.SysConfigMapper;
import com.mcc.system.service.ISysConfigService;

/**
 * 参数配置 服务层实现
 *
 * @author gxy
 */
@Service
public class SysConfigServiceImpl implements ISysConfigService {

    @Autowired
    private SysConfigMapper configMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        List<SysConfig> configsList = configMapper.selectList(null);
        for (SysConfig config : configsList) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    public SysConfig selectConfigById(Long configId) {
        return configMapper.selectById(configId);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("config_key", configKey);
        queryWrapper.last("limit 1");
        SysConfig retConfig = configMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfig config) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(config)) {
            queryWrapper.like(ObjectUtil.isNotEmpty(config.getConfigName()), "config_name", config.getConfigName());
            queryWrapper.eq(ObjectUtil.isNotEmpty(config.getConfigType()), "config_type", config.getConfigType());
            queryWrapper.like(ObjectUtil.isNotEmpty(config.getConfigKey()), "config_key", config.getConfigKey());
            queryWrapper.ge(ObjectUtil.isNotEmpty(config.getBeginTime()), "date_format(create_time,'%Y-%m-%d')", config.getBeginTime());
            queryWrapper.le(ObjectUtil.isNotEmpty(config.getEndTime()), "date_format(create_time,'%Y-%m-%d')", config.getEndTime());
        }
        return configMapper.selectList(queryWrapper);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config) {
        config.setCreateBy(SecurityUtils.getUsername());
        config.setCreateTime(new Date());
        int row = configMapper.insert(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config) {
        config.setUpdateBy(SecurityUtils.getUsername());
        config.setUpdateTime(new Date());
        int row = configMapper.updateById(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     * @return 结果
     */
    @Override
    public int deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new CustomException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
        }
        if (configIds.length == 0) return 0;
        int count = configMapper.deleteBatchIds(ListUtil.toList(configIds));
        if (count > 0) {
            Collection<String> keys = redisCache.keys(Constants.SYS_CONFIG_KEY + "*");
            redisCache.deleteObject(keys);
        }
        return count;
    }

    /**
     * 清空缓存数据
     */
    @Override
    public void clearCache() {
        Collection<String> keys = redisCache.keys(Constants.SYS_CONFIG_KEY + "*");
        redisCache.deleteObject(keys);
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("config_key", config.getConfigKey());
        queryWrapper.ne(ObjectUtil.isNotEmpty(config.getConfigId()), "config_id", config.getConfigId());
        return configMapper.selectCount(queryWrapper) == 0;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.SYS_CONFIG_KEY + configKey;
    }

    @Override
    public boolean setConfigValueByKey(String configKey, String configValue) {
        SysConfig sysConfig = getConfigByKey(configKey);
        if (sysConfig != null) {
            sysConfig.setConfigValue(Convert.toStr(configValue));
            sysConfig.setUpdateBy(SecurityUtils.getUsername());
            return updateConfig(sysConfig) > 0;
        }
        return false;
    }

    @Override
    public boolean setConfigValueByKeySystem(String configKey, String configValue) {
        SysConfig sysConfig = getConfigByKey(configKey);
        if (sysConfig != null) {
            sysConfig.setConfigValue(Convert.toStr(configValue));
            sysConfig.setUpdateBy("admin");
            return updateConfig(sysConfig) > 0;
        }
        return false;
    }

    private SysConfig getConfigByKey(String configKey) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("config_key", configKey);
        queryWrapper.last("limit 1");
        return configMapper.selectOne(queryWrapper);
    }
}
